/*
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package hextd.message;

import hextd.message.MessageFactory.NetworkMessage;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MessageSay implements Message {

	public NetworkMessage type = NetworkMessage.Say;
	public static String RegExp = "SAY ([-0-9]+) ([^\\n]+)";
	public static Pattern MessagePattern = Pattern.compile(MessageSay.RegExp);
	//
	private String message;
	private String text;
	private int senderId = -2;

	public static String formatMessage(int playerId, String text) {
		if (text.length() > 0) {
			String message = "";
			try {
				message = "SAY " + playerId + " " + URLEncoder.encode(text, "UTF-8");
			} catch (UnsupportedEncodingException ex) {
				Logger.getLogger(MessageSay.class.getName()).log(Level.SEVERE, null, ex);
			}
			return message;
		} else {
			return "";
		}
	}

	public MessageSay() {
	}

	private MessageSay(String message) {
		this.message = message;
		Matcher matcher = MessageSay.MessagePattern.matcher(message);
		if (matcher.matches()) {
			try {
				this.senderId = Integer.parseInt(matcher.group(1));
				this.text = URLDecoder.decode(matcher.group(2), "UTF-8");
			} catch (NumberFormatException e) {
				System.err.println("MessageSay: invalid id in: " + matcher.group(1));
			} catch (UnsupportedEncodingException ex) {
				Logger.getLogger(MessageSay.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
	}

	public String getText() {
		return this.text;
	}

	@Override
	public String getMessage() {
		return this.message;
	}

	@Override
	public Message initFromString(String message) {
		return new MessageSay(message);
	}

	@Override
	public int getSenderId() {
		return this.senderId;
	}

	@Override
	public void setSenderId(int id) {
		this.senderId = id;
		this.message = "SAY " + this.senderId + " " + this.text;
	}

	@Override
	public Pattern getPattern() {
		return MessageSay.MessagePattern;
	}

	@Override
	public NetworkMessage getType() {
		return this.type;
	}
}
